package com.hhx.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.awt.*;
import java.io.IOException;
import java.io.PrintWriter;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
//import org.json.JSONObject; // 导入 JSONObject 类
import com.hhx.entity.Goods;
import com.hhx.service.GoodsService;
import com.hhx.service.UserService;
import com.hhx.service.impl.GoodsServiceImpl;
import com.hhx.service.impl.UserServiceImpl;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.time.LocalDateTime;

@WebServlet(name = "goodsServlet", value = "/goodsServlet")
public class goodsServlet extends HttpServlet {
    private GoodsService service = new GoodsServiceImpl();
    private UserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String method = request.getParameter("method");
        if (method == null) {
            this.select(request, response);
        }else  if ("login".equals(method)){
            this.login(request, response);
        } else if ("getImg".equals(method)) {
            this.getImg(request, response);
        } else if ("add".equals(method)){
            this.add(request, response);
        } else if ("info".equals(method)) {
            this.info(request, response);
        }else if ("delete".equals(method)) {
            this.delete(request, response);
        }else if ("update".equals(method)) {
            this.update(request, response);
        } else if ("edit".equals(method)) {
            this.edit(request, response);
        } else if ("out".equals(method)) {
            this.out(request, response);
        }else {
            this.select(request, response);
        }
    }
    private void edit(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        try {
            request.setAttribute("goods", service.getById(request.getParameter("id")));
            request.getRequestDispatcher("update.jsp").forward(request, response);
        }catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "error get goods info");
        }
    }
    private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            String itemId = request.getParameter("itemId");
            String goodsName = request.getParameter("goodsName");
            String goodsType = request.getParameter("goodsType");
            String goodsBrand = request.getParameter("goodsBrand");
            double goodsPrice = Double.parseDouble(request.getParameter("goodsPrice"));
            Integer goodsSum = Integer.parseInt(request.getParameter("goodsSum"));
            String goodsDesc = request.getParameter("goodsDesc");
            double goodsDiscount = Double.parseDouble(request.getParameter("goodsDiscount"));
            String goodsImg = request.getParameter("goodsImg");
            // 获取当前时间作为 Timestamp
            Timestamp createDate = Timestamp.from(Instant.now());
            Goods goods = new Goods(Integer.parseInt(id), itemId, goodsName, goodsType, goodsBrand, goodsPrice, goodsSum, goodsDesc, goodsDiscount, goodsImg, createDate);
            System.out.println("goods: " + goods);
            String msg = (service.update(goods) > 0) ? "success update goods" : "error update goods";
            PrintWriter pw = response.getWriter();
            // 打印消息
//            pw.write("<script>alert('修改" + msg + "!');location.href='goodsServlet'</script>");
            pw.write("<script>location.href='goodsServlet'</script>");
            pw.write("<script>alert('修改" + msg + "!');</script>");
            pw.close();
        }catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "error update goods");
        }
    }
    private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            int result = service.delete(id);
            if (result > 0) {
                response.sendRedirect("goodsServlet");
            }
        }catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "error delete goods");
        }
    }
    private void info(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String id = request.getParameter("id");
            Goods goods = service.getById(id);

            request.setAttribute("goods", goods);
            request.getRequestDispatcher("detail.jsp").forward(request, response);
        }catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "error get goods info");
        }
    }
    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {

            String itemId = request.getParameter("itemId");
            String goodsName = request.getParameter("goodsName");
            String goodsType = request.getParameter("goodsType");
            String goodsBrand = request.getParameter("goodsBrand");
            double goodsPrice = Double.parseDouble(request.getParameter("goodsPrice"));
            Integer goodsSum = Integer.parseInt(request.getParameter("goodsSum"));
            String goodsDesc = request.getParameter("goodsDesc");
            double goodsDiscount = Double.parseDouble(request.getParameter("goodsDiscount"));
            String goodsImg = request.getParameter("goodsImg");
            // 获取当前时间作为 Timestamp
            Timestamp createDate = Timestamp.from(Instant.now());
            Goods goods = new Goods(0,itemId, goodsName, goodsType, goodsBrand, goodsPrice, goodsSum, goodsDesc, goodsDiscount, goodsImg, createDate);
            System.out.println("goods: " + goods);
            String msg = (service.add(goods)>0)?"success add goods":"error add goods";
            PrintWriter pw = response.getWriter();
            // 打印消息
//            pw.write("<script>alert('增加" + msg + "!');location.href='goodsServlet'</script>");
            pw.write("<script>location.href='goodsServlet'</script>");
            pw.write("<script>alert('增加" + msg +"!');</script>");
            pw.close();
        }catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "error add goods");
        }
    }
    private void getImg(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SmartUpload su = new SmartUpload();
        su.setCharset("utf-8");
        su.setAllowedFilesList("jpeg,jpg,png,gif");
        su.setMaxFileSize(1024 * 1024 * 10); // 10M
        su.initialize(this.getServletConfig(), request, response);
        String realPath = this.getServletContext().getRealPath("/");
        String path = realPath.substring(0, realPath.indexOf("out"));
        System.out.println("path--->"+path);
        String str = this.getServletContext().getRealPath("/images");
        System.out.println("str--->"+str);
        try {
            su.upload();    // 上传文件
            Files files = su.getFiles(); // 获取上传文件
            File file = files.getFile(0); // 获取第一个文件
            String fileName = file.getFileName(); // 获取文件名
            LocalDateTime date = LocalDateTime.now(); // 获取当前时间
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmssms"); // 时间格式化
            String name = dtf.format(date) + new Random().nextInt(100); // 重命名文件名
            String img = name + fileName.substring(fileName.lastIndexOf(".")); // 拼接文件名
            if (!img.isEmpty()){
                file.saveAs(path+"web/images/"+img);
                file.saveAs(str+"\\"+img);
            }else {
                img = "default.jpg";
            }
            System.out.println("img upload success");
            PrintWriter pw = response.getWriter();
            pw.write(img);
            pw.close();
//            response.setContentType("application/json;charset=UTF-8");
//            Map<String, Object> map = new HashMap<>();
//            map.put("img", img);
//            map.put("message", "cgimg upload success");
//            map.put("status", 200);
//            return map;

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "error upload img");
//            return null;
        }
    }
    private void select(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       try {
           int current = (request.getParameter("current") == null ? 1 : Integer.parseInt(request.getParameter("current")));
           int limit = 20;
           String name = request.getParameter("name");
           int count = service.count(name);
           int pages = (count/limit==0)?count/limit:count/limit+1;
           if (current<1 ||current>pages){
               current = 1;
           }
           request.setAttribute("list", service.getAll(name, current, limit));
           request.setAttribute("current", current);
           request.setAttribute("pages", pages);
           request.setAttribute("name", name);
           request.getRequestDispatcher("list.jsp").forward(request, response);
       }catch (Exception e) {
           e.printStackTrace();
           response.sendRedirect("error.jsp");
       }
    }
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            boolean flag = userService.authenticate(username, password);
            if (flag) {
                request.getSession().setAttribute("user", username);
                response.sendRedirect("goodsServlet");
            }else {
                // 设置错误信息，以便 login.jsp 可以显示给用户
                request.setAttribute("error", "Invalid username or password.");
                request.getRequestDispatcher("/login.jsp").forward(request, response); // 使用请求转发
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "An error occurred during login.");
            request.getRequestDispatcher("/error.jsp").forward(request, response); // 错误页面也使用请求转发
        }
    }
    private void out(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect("login.jsp");
    }
}
